/*
 * Created by JFormDesigner on Sun Oct 19 23:22:21 CST 2025
 */

package com.yeban.javase.day10.swing_learn.other;

import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.*;
import java.util.List;

/**
 * @author yeban
 */
public class MyTable extends JFrame {

    public static void main(String[] args) {
        (new MyTable()).setVisible(true);
    }

    public MyTable() {
        initComponents();

        // 做表格数据
        List<User> list = new ArrayList<>();
        list.add(new User("张三",22));
        list.add(new User("李四",23));
        list.add(new User("王五",22));
        list.add(new User("赵六",21));
        list.add(new User("王二",22));

        // 表格标题
        String[] titles = {"编号", "姓名", "年龄"};
        // 表格数据 行数为表格数据的长度、列数为标头长度
        Object[][] data = new Object[list.size()][titles.length];
        int index = 0;
        // 给每一行填充数据 编号、姓名、年龄
        for (int i = 0; i < data.length; i++) {
            data[i] = new Object[] {
                    ++index,
                    list.get(i).getName(),
                    list.get(i).getAge()
            };
        }
        // 封装模型数据，对于表格考虑两个数据：表头和表格数据
        DefaultTableModel model = new DefaultTableModel(data, titles);  // 需要添加数据、表格

        // 设置数据
        table1.setModel(model);
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        scrollPane1 = new JScrollPane();
        table1 = new JTable();

        //======== this ========
        Container contentPane = getContentPane();
        contentPane.setLayout(null);

        //======== scrollPane1 ========
        {

            //---- table1 ----
            table1.setModel(new DefaultTableModel(
                new Object[][] {
                    {null, null, null},
                    {null, null, null},
                    {null, null, null},
                    {null, null, null},
                },
                new String[] {
                    null, null, null
                }
            ));
            scrollPane1.setViewportView(table1);
        }
        contentPane.add(scrollPane1);
        scrollPane1.setBounds(75, 30, 275, 235);

        contentPane.setPreferredSize(new Dimension(470, 365));
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JScrollPane scrollPane1;
    private JTable table1;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
